package bb.lanxing.activity.base;

import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.FragmentActivity;

import com.google.android.material.snackbar.Snackbar;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.interfaces.IPermissionInspector;
import bb.lanxing.common.config.Constants;
import bb.lanxing.common.messager.EventMessageListener;
import bb.lanxing.lib.widget.utils.ColorUtil;
import bb.lanxing.manager.ISubscriptionManager;
import bb.lanxing.mvp.base.IViewInterface;
import bb.lanxing.util.DialogUtil;
import bb.lanxing.util.ui.CircularProgressDialog;
import bb.lanxing.util.ui.StatusBarUtil;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

public abstract class BaseActivity extends AppCompatActivity implements IViewInterface, IPermissionInspector, EventMessageListener {
    private final ISubscriptionManager iSubscriptionManager = new ISubscriptionManager() {
        private final CompositeSubscription compositeSubscription = new CompositeSubscription();

        @Override
        public void unsubscribe() {
            compositeSubscription.unsubscribe();
        }

        @Override
        public void cancelSubscription(@NonNull Subscription subscription) {
            if (!subscription.isUnsubscribed()) {
                subscription.unsubscribe();
            }
            removeSubscription(subscription);
        }

        @Override
        public void removeSubscription(@NonNull Subscription subscription) {
            compositeSubscription.remove(subscription);
        }

        @Override
        public void addSubscription(@NonNull Subscription subscription) {
            compositeSubscription.add(subscription);
        }
    };
    protected CircularProgressDialog circularProgressDialog;
    protected Context context;
    protected Handler baseHandler = new Handler();
    protected boolean mIsPaused = false;
    private TextView titleView;
    private DialogUtil.LoadingPopupWindow mProgressPopWindow = null;
    private boolean homeAsBack = false;
    private boolean centerTitle = false;

    public void addSubscription(Subscription subscription) {
        iSubscriptionManager.addSubscription(subscription);
    }

    public void removeSubscription(Subscription subscription) {
        iSubscriptionManager.removeSubscription(subscription);
    }

    public void cancelSubscription(Subscription subscription) {
        if (!subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
        removeSubscription(subscription);
    }

    @Override
    public FragmentActivity getActivity() {
        return this;
    }

    public boolean onHomeBack() {
        return false;
    }

    @Override
    public boolean onMessage(int i, int i2, int i3, Object obj, Bundle bundle) {
        return false;
    }

    protected boolean onPermissionDenied(String[] strArr) {
        return false;
    }

    protected void onPermissionGranted() {
    }

    public boolean orientationPortrait() {
        return true;
    }

    protected boolean registerMessageEvent() {
        return false;
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        this.context = this;
        String simpleName = getClass().getSimpleName();
        Log.w("CurrentActivity", "name == " + simpleName);
        if (orientationPortrait()) {
            try {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (registerMessageEvent()) {
            App.getContext().getMessageSender().registerListener(this);
        }
        //if (RxPermissionUtil.checkUserAgreement() || simpleName.equals(MainActivity.class.getSimpleName())) {
        //    return;
        //}
        //finish();

    }

    public Toolbar setupActionBar(boolean homeAsBack) {
        return setupActionBar(homeAsBack, -1, true);
    }

    public Toolbar setupActionBar(boolean homeAsBack, int i, boolean centerTitle) {
        return setupActionBar(homeAsBack, i, centerTitle, true);
    }

    public Toolbar setupActionBar(boolean homeAsBack, int i, boolean centerTitle, boolean z3) {
        Toolbar toolbar = findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            this.titleView = findViewById(R.id.toolbar_title);
            this.homeAsBack = homeAsBack;
            ActionBar supportActionBar = getSupportActionBar();
            if (supportActionBar != null) {
                supportActionBar.setDisplayHomeAsUpEnabled(homeAsBack);
                this.centerTitle = centerTitle;
                supportActionBar.setDisplayShowTitleEnabled(true);
                if (centerTitle) {
                    CharSequence title = supportActionBar.getTitle();
                    if (!TextUtils.isEmpty(title) && this.titleView != null) {
                        supportActionBar.setTitle("");
                        this.titleView.setText(title);
                    }
                } else {
                    toolbar.removeView(this.titleView);
                    this.titleView = null;
                }
                if (i <= 0) {
                    TypedArray obtainStyledAttributes = toolbar.getContext().obtainStyledAttributes(null, new int[]{R.attr.action_back_icon});
                    Drawable drawable = obtainStyledAttributes.getDrawable(0);
                    obtainStyledAttributes.recycle();
                    if (drawable == null) {
                        supportActionBar.setHomeAsUpIndicator(R.drawable.action_bar_back);
                    } else {
                        supportActionBar.setHomeAsUpIndicator(drawable);
                    }
                } else {
                    supportActionBar.setHomeAsUpIndicator(i);
                }
            }
            if (z3) {
                initStatusBar(toolbar);
            }
            return toolbar;
        }
        return null;
    }

    protected void initStatusBar(View view) {
        TypedArray obtainStyledAttributes = obtainStyledAttributes(null, new int[]{android.R.attr.colorPrimaryDark});
        int color = obtainStyledAttributes.getColor(0, ViewCompat.MEASURED_STATE_MASK);
        obtainStyledAttributes.recycle();
        if (ColorUtil.isLight(color)) {
            if (!StatusBarUtil.darkMode(this, true)) {
                setStatusBarForKitKat(view, color);
            }
        } else {
            setStatusBarForKitKat(view, color);
        }
    }

    private void setStatusBarForKitKat(View view, int i) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        StatusBarUtil.setTranslucentView((ViewGroup) window.getDecorView(), i);
        if (view != null) {
            StatusBarUtil.setPaddingSmart(this, view);
        }
    }

    @Override
    public void setTitle(CharSequence charSequence) {
        TextView textView;
        if (this.centerTitle && (textView = this.titleView) != null) {
            textView.setText(charSequence);
            this.titleView.setVisibility(TextUtils.isEmpty(charSequence) ? View.GONE : View.VISIBLE);
            return;
        }
        super.setTitle(charSequence);
    }

    public CharSequence getActionTitle() {
        TextView textView;
        if (this.centerTitle && (textView = this.titleView) != null) {
            return textView.getText();
        }
        return getTitle();
    }

    public void setTitleTextColor(int i) {
        TextView textView = this.titleView;
        if (textView != null) {
            textView.setTextColor(ContextCompat.getColor(this, i));
        }
    }

    public boolean immersiveStatusBar(int i, boolean z) {
        StatusBarUtil.immersive(this, i);
        return darkStatusBarIcon(z);
    }

    public boolean darkStatusBarIcon(boolean z) {
        if (StatusBarUtil.darkMode(this, z)) {
            return true;
        }
        StatusBarUtil.shadowStatusBar(this, z);
        return false;
    }

    public void autoFitStatusBarIconColor() {
        TypedArray obtainStyledAttributes = obtainStyledAttributes(null, new int[]{android.R.attr.colorPrimaryDark});
        int color = obtainStyledAttributes.getColor(0, ViewCompat.MEASURED_STATE_MASK);
        obtainStyledAttributes.recycle();
        darkStatusBarIcon(ColorUtil.isLight(color));
    }

    public void shadowTranslucent(boolean z) {
        StatusBarUtil.shadowStatusBar(this, z);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem menuItem) {
        if (this.homeAsBack && menuItem.getItemId() == android.R.id.home && !onHomeBack()) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(menuItem);
    }

    @Override
    public void onResume() {
        super.onResume();
        this.mIsPaused = false;
        MobclickAgent.onPageStart(getClass().getName());
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        this.mIsPaused = true;
        MobclickAgent.onPageEnd(getClass().getName());
        MobclickAgent.onPause(this);
    }

    @Override
    public void onDestroy() {
        iSubscriptionManager.unsubscribe();
        dismissLoadingDialog();
        if (registerMessageEvent()) {
            App.getContext().getMessageSender().unregisterListener(this);
        }
        super.onDestroy();
    }

    @Deprecated
    public void showMyProgressDialog() {
        showLoadingDialogInternal(getString(R.string.dialog_loading), true, null);
    }

    @Deprecated
    public void showMyProgressDialog(int i) {
        showLoadingDialogInternal(getString(i), true, null);
    }

    @Deprecated
    public void showMyProgressDialog(String str) {
        showLoadingDialogInternal(str, true, null);
    }

    @Override
    public void showLoadingDialog(int i, boolean z, DialogInterface.OnCancelListener onCancelListener) {
        showLoadingDialog(getString(i), z, onCancelListener);
    }

    @Override
    public void showLoadingDialog(final CharSequence charSequence, boolean z, DialogInterface.OnCancelListener onCancelListener) {
        if (this.circularProgressDialog == null) {
            this.circularProgressDialog = new CircularProgressDialog(this, z, false, onCancelListener);
        }
        if (Looper.myLooper() == Looper.getMainLooper()) {
            this.circularProgressDialog.show(charSequence);
        } else {
            App.get().getHandler().post(() -> BaseActivity.this.circularProgressDialog.show(charSequence));
        }
    }

    @Override
    public void showLoadingDialog(int i, boolean cancelable) {
        showLoadingDialogInternal(getString(i), cancelable, null);
    }

    @Override
    public void showLoadingDialog(CharSequence charSequence, boolean cancelable) {
        showLoadingDialogInternal(charSequence, cancelable, null);
    }

    @Override
    public void showLoadingDialog(int i, DialogInterface.OnCancelListener onCancelListener) {
        showLoadingDialogInternal(getString(i), true, onCancelListener);
    }

    @Override
    public void showLoadingDialog(CharSequence charSequence, DialogInterface.OnCancelListener onCancelListener) {
        showLoadingDialogInternal(charSequence, true, onCancelListener);
    }

    public void showLoadingDialogInternal(final CharSequence charSequence, boolean cancelable, DialogInterface.OnCancelListener onCancelListener) {
        if (this.circularProgressDialog == null) {
            this.circularProgressDialog = new CircularProgressDialog(this, cancelable, false, onCancelListener);
        }

        this.baseHandler.post(() -> {
            try {
                if (BaseActivity.this.isFinishing()) {
                    return;
                }
                circularProgressDialog.show(charSequence);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void dismissLoadingDialog() {
        Log.d(Constants.TAG, getClass() + " closeWaitingDialog ====== " + this.circularProgressDialog);

        this.baseHandler.post(() -> {
            if (circularProgressDialog != null) {
                try {
                    circularProgressDialog.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                circularProgressDialog = null;
            }
        });
    }

    @Override
    public void snack(CharSequence charSequence) {
        if (!isFinishing()) {
            Snackbar.make(getWindow().getDecorView(), charSequence, 0).setTextColor(-1).show();
        }
    }

    @Override
    public void snack(int i) {
        if (!isFinishing()) {
            Snackbar.make(getWindow().getDecorView(), i, -1).setTextColor(-1).show();
        }
    }

    @Override
    public void snackLong(CharSequence charSequence) {
        if (!isFinishing()) {
            Snackbar.make(getWindow().getDecorView(), charSequence, 0).setTextColor(-1).show();
        }
    }

    @Override
    public void snackLong(int i) {
        if (!isFinishing()) {
            Snackbar.make(getWindow().getDecorView(), i, 0).setTextColor(-1).show();
        }
    }

    @Override
    public void snack(CharSequence charSequence, boolean z) {
        if (!isFinishing()) {
            Snackbar actionTextColor = Snackbar.make(getWindow().getDecorView(), charSequence, 0).setTextColor(-1).setActionTextColor(-1);
            actionTextColor.getView().setBackgroundColor(getResources().getColor(z ? R.color.snack_succes : R.color.common_red));
            actionTextColor.show();
        }
    }

    @Override
    public void snack(int i, boolean z) {
        if (!isFinishing()) {
            snack(getResources().getString(i), z);
        }
    }

    @Override
    public void snackLong(CharSequence charSequence, boolean z) {
        if (!isFinishing()) {
            Snackbar actionTextColor = Snackbar.make(getWindow().getDecorView(), charSequence, 0).setTextColor(-1).setActionTextColor(-1);
            actionTextColor.getView().setBackgroundColor(getResources().getColor(z ? R.color.snack_succes : R.color.common_red));
            actionTextColor.show();
        }
    }

    @Override
    public void snackLong(int i, boolean z) {
        if (!isFinishing()) {
            snackLong(getResources().getString(i), z);
        }
    }

    @Override
    public void snackTop(CharSequence charSequence) {
        if (!isFinishing()) {
            // TopSnackBar.Companion.makeText(getWindow().getDecorView(), charSequence,
            // TopSnackBar.Companion.getLENGTH_SHORT()).showWithAnimate();
        }
    }

    @Override
    public void snackTop(int i) {
        if (!isFinishing()) {
            // TopSnackBar.Companion.makeText(getWindow().getDecorView(), i,
            // TopSnackBar.Companion.getLENGTH_SHORT()).showWithAnimate();
        }
    }

    @Override
    public void snackTopLong(CharSequence charSequence) {
        if (!isFinishing()) {
            // TopSnackBar.Companion.makeText(getWindow().getDecorView(), charSequence,
            // TopSnackBar.Companion.getLENGTH_LONG()).showWithAnimate();
        }
    }

    @Override
    public void snackTopLong(int i) {
        if (!isFinishing()) {
            // TopSnackBar.Companion.makeText(getWindow().getDecorView(), i,
            // TopSnackBar.Companion.getLENGTH_LONG()).showWithAnimate();
        }
    }

    @Override
    public void snackTop(CharSequence charSequence, int i, int i2) {
        if (!isFinishing()) {
            // TopSnackBar.Companion.makeText(getWindow().getDecorView(), charSequence,
            // TopSnackBar.Companion.getLENGTH_SHORT(), i, i2).showWithAnimate();
        }
    }

    @Override
    public void snackTop(int i, int i2, int i3) {
        if (!isFinishing()) {
            // TopSnackBar.Companion.makeText(getWindow().getDecorView(), i, TopSnackBar.Companion.getLENGTH_SHORT(),
            // i2, i3).showWithAnimate();
        }
    }

    @Override
    public void snackTopLong(CharSequence charSequence, int i, int i2) {
        if (!isFinishing()) {
            // TopSnackBar.Companion.makeText(getWindow().getDecorView(), charSequence,
            // TopSnackBar.Companion.getLENGTH_LONG(), i, i2).showWithAnimate();
        }
    }

    @Override
    public void snackTopLong(int i, int i2, int i3) {
        if (!isFinishing()) {
            // TopSnackBar.Companion.makeText(getWindow().getDecorView(), i, TopSnackBar.Companion.getLENGTH_LONG(), i2,
            // i3).showWithAnimate();
        }
    }

    public void initLoadingPopWindow() {
        if (this.mProgressPopWindow == null) {
            this.mProgressPopWindow = DialogUtil.initProgressDialog(this, new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    closePopWindow();
                }
            });
        }
    }

    public void showLoadingPopWindow(String str) {
        showLoadingPopWindow(str, true);
    }

    public void showLoadingPopWindow(String str, boolean z) {
        initLoadingPopWindow();
        DialogUtil.LoadingPopupWindow loadingPopupWindow = this.mProgressPopWindow;
        if (loadingPopupWindow != null) {
            loadingPopupWindow.setFocusable(z);
            DialogUtil.showProgressDialog(this, this.mProgressPopWindow, str);
        }
    }

    public void showLoadingPopWindow() {
        showLoadingPopWindow("");
    }

    public void closePopWindow() {
        this.baseHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mProgressPopWindow != null) {
                    DialogUtil.hideDialog(mProgressPopWindow);
                    mProgressPopWindow = null;
                }
            }
        });
    }

    @Override
    public void dismissLoadingDialogWithDoneAnimation() {
        Log.d(Constants.TAG, getClass() + " dismissLoadingDialogWithDoneAnimation ====== " + this.circularProgressDialog);
        if (Looper.myLooper() == Looper.getMainLooper()) {
            CircularProgressDialog circularProgressDialog = this.circularProgressDialog;
            if (circularProgressDialog == null) {
                return;
            }
            circularProgressDialog.dismissWithDoneAnimation();
            return;
        }
        App.getContext().getHandler().post(() -> {
            if (circularProgressDialog != null) {
                circularProgressDialog.dismissWithDoneAnimation();
            }
        });
    }

    public boolean isPaused() {
        return this.mIsPaused;
    }

    @Override
    public void toast(final CharSequence charSequence) {
        if (TextUtils.isEmpty(charSequence)) {
            return;
        }
        if (Looper.myLooper() == Looper.getMainLooper()) {
            Toast.makeText(this, charSequence, Toast.LENGTH_SHORT).show();
        } else {
            runOnUiThread(() -> Toast.makeText(BaseActivity.this, charSequence, Toast.LENGTH_SHORT).show());
        }
    }

    @Override
    public void toast(int i) {
        toast(getString(i));
    }

    @Override
    public void toastLong(final CharSequence charSequence) {
        if (TextUtils.isEmpty(charSequence)) {
            return;
        }
        if (Looper.myLooper() == Looper.getMainLooper()) {
            Toast.makeText(this, charSequence, Toast.LENGTH_LONG).show();
        } else {
            runOnUiThread(() -> Toast.makeText(BaseActivity.this, charSequence, Toast.LENGTH_LONG).show());
        }
    }

    @Override
    public void toastLong(int i) {
        toastLong(getString(i));
    }

    public void sendMessage(int i) {
        sendMessageDelayed(i, 0, 0, null, null, 0L);
    }

    public void sendMessage(int i, Bundle bundle) {
        sendMessageDelayed(i, 0, 0, null, bundle, 0L);
    }

    public void sendMessage(int i, Object obj) {
        sendMessageDelayed(i, 0, 0, obj, null, 0L);
    }

    public void sendMessage(int i, int i2, int i3) {
        sendMessageDelayed(i, i2, i3, null, null, 0L);
    }

    public void sendMessage(int i, int i2, int i3, Bundle bundle) {
        sendMessageDelayed(i, i2, i3, null, bundle, 0L);
    }

    public void sendMessage(int i, int i2, int i3, Object obj) {
        sendMessageDelayed(i, i2, i3, obj, null, 0L);
    }

    public void sendMessage(int i, int i2, int i3, Object obj, Bundle bundle) {
        sendMessageDelayed(i, i2, i3, obj, bundle, 0L);
    }

    public void sendMessageDelayed(int i, int i2, int i3, Object obj, Bundle bundle, long j) {
        App.getContext().getMessageSender().sendMessageDelayed(i, i2, i3, obj, bundle, j);
    }

    public void cancelMessage(int i) {
        App.getContext().getMessageSender().cancelMessage(i);
    }

    public void cancelMessage(int i, Object obj) {
        App.getContext().getMessageSender().cancelMessage(i, obj);
    }

    @Override
    public boolean checkAndRequestPermissions(String[] strArr, int i) {
        return checkAndRequestPermissions(strArr, i > 0 ? getString(i) : null);
    }

    @Override
    public boolean checkAndRequestPermissions(String[] strArr, CharSequence charSequence) {
        final String[] checkPermissions;
        if (strArr == null || strArr.length == 0 || (checkPermissions = checkPermissions(strArr)) == null) {
            return true;
        }
        boolean z = false;
        for (String str : checkPermissions) {
            z |= ActivityCompat.shouldShowRequestPermissionRationale(this, str);
        }
        if (z && !TextUtils.isEmpty(charSequence)) {
            DialogUtil.adjustDialogGravityCenter(new AlertDialog.Builder(this).setTitle(R.string.dialog_prompt).setMessage(charSequence).setPositiveButton(R.string.confirm, (dialogInterface, i) -> ActivityCompat.requestPermissions(BaseActivity.this, checkPermissions, 1)).setNegativeButton(R.string.cancel, (dialogInterface, i) -> {
                if (!onPermissionDenied(checkPermissions)) {
                    toast(R.string.sport_all_permission_title);
                }
            }).setCancelable(false).show());
        } else {
            ActivityCompat.requestPermissions(this, checkPermissions, 1);
        }
        return false;
    }

    @Override
    public boolean checkAndRequestPermissionsWithRationale(String[] strArr, IPermissionInspector.PermissionRationaleCallback permissionRationaleCallback) {
        final String[] checkPermissions;
        if (strArr == null || strArr.length <= 0 || (checkPermissions = checkPermissions(strArr)) == null) {
            return true;
        }
        if (permissionRationaleCallback == null) {
            return false;
        }
        permissionRationaleCallback.onRequestRationale(new IPermissionInspector.PermissionRationaleConfirmCallback() {
            @Override
            public String[] getCurrentRequiredPermissions() {
                return checkPermissions;
            }

            @Override
            public void onRequestRationaleConfirmed() {
                ActivityCompat.requestPermissions(BaseActivity.this, checkPermissions, 1);
            }
        });
        return false;
    }

    private String[] checkPermissions(String[] strArr) {
        ArrayList arrayList = new ArrayList();
        for (String str : strArr) {
            if (ContextCompat.checkSelfPermission(this, str) == -1) {
                arrayList.add(str);
            }
        }
        if (arrayList.isEmpty()) {
            return null;
        }
        return (String[]) arrayList.toArray(new String[arrayList.size()]);
    }

    @Override
    public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) {
        super.onRequestPermissionsResult(i, strArr, iArr);
        if (i == 1) {
            ArrayList arrayList = new ArrayList();
            for (int i2 = 0; i2 < iArr.length; i2++) {
                if (iArr[i2] == -1) {
                    arrayList.add(strArr[i2]);
                }
            }
            if (!arrayList.isEmpty()) {
                if (onPermissionDenied((String[]) arrayList.toArray(new String[arrayList.size()]))) {
                    return;
                }
                toast(R.string.sport_all_permission_title);
                return;
            }
            onPermissionGranted();
        }
    }

    @Override
    protected void onStop() {
        dismissLoadingDialog();
        super.onStop();
    }
}
